package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import com.itheima.utils.QiniuUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
public class AddressController {

    @Reference
    private AddressService addressService;

    @Autowired
    private JedisPool jedisPool;

    // /address/findPage
     // 分页查询
    @RequestMapping("/address/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return addressService.findPage(queryPageBean);
    }

    // /address/upload
    // 文件上传
    @RequestMapping("/address/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        try {
            //获取 在上传方本地的的文件名
            String originalFilename = imgFile.getOriginalFilename();
            //获取最后一个 . 的 索引值
            int index = originalFilename.lastIndexOf(".");
            //截取 .后缀名
            String substring = originalFilename.substring(index - 1);
            String fileName = UUID.randomUUID().toString()+substring;
            System.out.println(fileName);
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);

            //如果最后上传没报错，则将文件名 存放进set集合
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    // /address/add
    // 新增
    @RequestMapping("/address/add")
    public Result add(@RequestBody Address address){
        return addressService.add(address);
    }

    // /address/delete
    @RequestMapping("/address/delete")
    public Result delete(Integer id){
        return addressService.delete(id);
    }

    // /edit/findByid
    @RequestMapping("/edit/findByid")
    public Result findByid(Integer id){
        return addressService.findByid(id);
    }

    // /address/update
    @RequestMapping("/address/update")
    public Result update(@RequestBody Address address){
        return addressService.update(address);
    }
}
